package com.zh.system.controller;

import com.zh.common.annotation.NeedAuth;
import com.zh.common.annotation.NeedRoles;
import com.zh.common.annotation.Operator;
import com.zh.common.constant.AuthConstant;
import com.zh.system.domain.dto.AskAiDto;
import com.zh.system.domain.dto.CrawlDto;
import com.zh.system.service.SystemService;
import com.zh.web.base.ApiResult;
import com.zh.web.base.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.time.LocalDateTime;

@Valid
@Slf4j
@RestController
@RequestMapping("/system")
@RequiredArgsConstructor
@Api(tags = "系统服务-系统工具接口", value = "system need auth")
@Operator
public class SystemController extends BaseController {

    private final SystemService systemService;

    @PostMapping("/crawl")
    @ApiOperation("爬虫开启-关闭")
    public ApiResult<String> crawl(@RequestBody CrawlDto crawlDto) {
        return buildMsgPackage(systemService.switchCrawl(crawlDto));
    }

    @ApiOperation("请求Ai预检参数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "Bearer token", required = true, dataType = "string", paramType = "header")
    })
    @NeedAuth(roles = {@NeedRoles(value = {AuthConstant.USER})})
    @PostMapping("/preArgs")
    public ApiResult<String> receiveKeywordBeforeAskAi(@RequestBody AskAiDto askAiDto, HttpServletRequest request) {
        return buildSuccessPackage(systemService.receiveKeywordBeforeAskAi(askAiDto, request));
    }

    @GetMapping(value = "/ai", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @ApiOperation(value = "请求Ai 需要限流,验证身份", hidden = true)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "Bearer token", required = true, dataType = "string", paramType = "header")
    })
    @NeedAuth(roles = {@NeedRoles(value = {AuthConstant.USER})})
    public SseEmitter askAi(@RequestParam Long id) throws IOException {
        return systemService.askAi(id);
    }

    @GetMapping
    @ApiOperation("测试")
    public ApiResult<String> test() {
        return buildMsgPackage("success");
    }
}